//
//  PersonalCenterViewController.m
//  QRMaster
//
//  Created by wangqiang on 15/3/21.
//  Copyright (c) 2015年 wangqiang. All rights reserved.

#import "PersonalCenterViewController.h"
#import "LineView.h"

#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "SystemSetViewController.h"
#import "StartPageController.h"
#import "Reachability.h"
#import "UIImageView+WebCache.h"
#import "ChangeHeadImgViewController.h"
#import "TouchBtnColor.h"
#import "GuestViewController.h"
#import "OpertionPlist.h"
#import "GesturePasswordController.h"
#import "Base64.h"
#import "KeychainItemWrapper.h"
#import "userInfoModel.h"
#import "UserInfoLogic.h"
#import "MJExtension.h"

#define FONT [UIFont systemFontOfSize:16.0]
#define FONTTWO [UIFont systemFontOfSize:14.0]

@interface PersonalCenterViewController ()<UIAlertViewDelegate,UINavigationControllerDelegate>
{
    NSString  * userNameStr;
    NSString * telePhoneStr;
    NSString * emailStr;
    NSString * callPhoneStr;
    UIImageView * titleImgView;
    NSString * headurl;
    NSUserDefaults * userInfo;
    NSInteger tokeCount;
    
    NSArray *iconArray;//cell前的图片
    NSArray *nameArray;//title
    UITableView *personTableView;
}
@end

@implementation PersonalCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    iconArray=[[NSArray alloc]initWithObjects:@"ic_加载头像212",@"ic_tel",@"ic_mail",@"ic_setA",@"ic_kefu", nil];
    
    nameArray=[[NSArray alloc]initWithObjects:NSLocalizedString(@"mineTelePhone", nil),NSLocalizedString(@"mineEmail", nil),NSLocalizedString(@"mineSetting", nil),NSLocalizedString(@"ServiceTelePhone", nil),nil];
    userInfo = [NSUserDefaults standardUserDefaults];
    tokeCount = 0;
    
    personTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT) style:UITableViewStylePlain];
    personTableView.delegate=self;
    personTableView.dataSource=self;
    personTableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    personTableView.separatorColor=[UIColor grayColor];
    [self.view addSubview:personTableView];
    [self setExtraCellLineHidden:personTableView];
    personTableView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
        [self getData];
    }];
    [self getDataFromDisk];
    [self getData];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [personTableView reloadData];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationItem.title=NSLocalizedString(@"mine", nil);
    nameArray=[[NSArray alloc]initWithObjects:NSLocalizedString(@"mineTelePhone", nil),NSLocalizedString(@"mineEmail", nil),NSLocalizedString(@"mineSetting", nil),NSLocalizedString(@"ServiceTelePhone", nil),nil];
    [personTableView reloadData];
    //    telePhoneStr = NSLocalizedString(@"mineTelePhone", nil);
    //    emailStr = NSLocalizedString(@"mineEmail", nil);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenCheck) name:@"tokenCheck"  object:nil];
    
    
}

-(void)getDataFromDisk
{
    __block userInfoModel *userModel = [[userInfoModel alloc]init];
    UserInfoLogic *userLogic = [[UserInfoLogic alloc]init];

    [userLogic queryUserInfo:^(userInfoModel *myUserModel)
    {
        userModel =myUserModel;
    }
     ];
    
    userNameStr  = userModel.name;
    telePhoneStr = userModel.mobile;
    emailStr     = userModel.email;
    headurl      = userModel.headUrl;
    callPhoneStr = @"020-32209192";
}

//获取个人信息
-(void)getData;
{
    if ([self IsHaveNetwork]) {
        [personTableView.mj_header endRefreshing];
        return;
    }
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    RequestNetWork * rn = [[RequestNetWork alloc]init];
    [rn initWithPath:POST(GETINFO) params:postDict block:^(id downLoadData, id error) {
        if ([downLoadData objectForKey:@"data"] != nil) {
            [self analysisUserInfoData:[downLoadData objectForKey:@"data"]];
            
        }
        else if (error != nil) {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        
    }];
    [personTableView reloadData];
    [personTableView.mj_header endRefreshing];
    
}

-(void)analysisUserInfoData:(NSDictionary *)data
{
    userInfoModel *userModel = [userInfoModel mj_objectWithKeyValues:data];
    userModel.uid=[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"];
    UserInfoLogic *userLogic = [[UserInfoLogic alloc]init];
    [userLogic deleteTable];
    [userLogic insertUserInfo:userModel];
    
    userNameStr =[data objectForKey:@"name"];
    telePhoneStr = [data objectForKey:@"mobile"];
    emailStr = [data objectForKey:@"email"];
    headurl = [data objectForKey:@"headUrl"];
    
    NSString * gesture = [data objectForKey:@"gesture"];
    //    保存手势密码
    if (![gesture isEqualToString:@""]) {
        NSString * decodeString = [NSString stringWithFormat:@"%@",[gesture base64DecodedString]];
        [userInfo setValue:decodeString forKey:GUESTUREKEY];
    }
    [personTableView reloadData];
}

#pragma mark -UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return iconArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

#pragma mark - tableView Delegate方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *leftIdentifier = @"MineIndentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:leftIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:leftIdentifier];
        cell.backgroundColor = [UIColor whiteColor];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    for (UIView *vw in cell.contentView.subviews) {
        [vw removeFromSuperview];
    }
   
    
    UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(20, 17.5, 15, 15)];
    if(indexPath.section==0)
    {
        img.frame=CGRectMake(10, 10, 70, 70);
        img.layer.cornerRadius=35;
        img.userInteractionEnabled=YES;
        img.layer.masksToBounds = YES; // 隐藏边界
        img.layer.borderWidth = 1;  // 给图层添加一个有色边框
//        img.layer.borderColor = [UIColor colorWithRed:0.52 green:0.09 blue:0.07 alpha:1].CGColor;
        img.layer.borderColor = (__bridge CGColorRef __nullable)([UIColor clearColor]);
        [img sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HEADERURL,headurl]] placeholderImage:[UIImage imageNamed:@"96人像"]];
        UITapGestureRecognizer * titleImgViewTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeTitleImg)];
        [img addGestureRecognizer:titleImgViewTap];
    }
    
    if (indexPath.section==3) {
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section != 0) {
         img.image=[UIImage imageNamed:[iconArray objectAtIndex:indexPath.section]];
    }
    [cell.contentView addSubview:img];
    
    if (indexPath.section!=0) {
        UILabel *lb=[[UILabel alloc]initWithFrame:CGRectMake(50, 10, UI_SCREEN_WIDTH - 80, 30)];
        lb.backgroundColor=[UIColor clearColor];
        lb.text=[nameArray objectAtIndex:indexPath.section-1];
        lb.font=[UIFont systemFontOfSize:14.0f];
        [cell.contentView addSubview:lb];
    }
    UIView *lineView=[[UIView alloc]initWithFrame:CGRectMake(0, 49, UI_SCREEN_WIDTH, 1)];
    if(indexPath.section==0)
    {
        lineView.frame=CGRectMake(0, 89, UI_SCREEN_WIDTH, 0.5);
    }
    lineView.backgroundColor=RGBA(193, 193, 193, 1.0);
//    UIColorFromRGB(0x333333);
    [cell.contentView addSubview:lineView];
    
    
    if (indexPath.section!=3)
    {
        UILabel *lb = [[UILabel alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH-160, 10, 140, 30)];
        lb.font=[UIFont systemFontOfSize:14.0f];
        lb.textAlignment = NSTextAlignmentRight;
        if (indexPath.section == 0)
        {
            lb.frame= CGRectMake(80, 30, UI_SCREEN_WIDTH - 20, 30);
            lb.textAlignment = NSTextAlignmentLeft;
            lb.textColor = [UIColor blackColor];
            lb.text = userNameStr;
        }
        else if (indexPath.section == 1)
        {
            lb.text = telePhoneStr;
        }
        else if (indexPath.section == 2)
        {
            lb.text = emailStr;
        }
        else if (indexPath.section == 4)
        {
            lb.text = callPhoneStr;
        }
        [cell.contentView addSubview:lb];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==1)
    {
        
    }
    else if (indexPath.section==2)
    {
        
    }
    else if (indexPath.section==3)
    {
        [self setClick];
        
    }
    else if (indexPath.section==4)
    {
        [self callTap];
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height=5.0f;
    if (indexPath.section==0)
    {
        height=90.0f;
    }
    else
    {
        height=50.0f;
    }
    return height;
}

//section头部间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    float height=5;
    if(section==0)
    {
        height=0.1;
    }
    return height;//section头部高度
}

//section头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    float height=5;
    if(section==0)
    {
        height=0.0001;
    }
    
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, height)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //    if (buttonIndex == 1) {
    //toke不通过清除所有东西
    StartPageController * spc = [[StartPageController alloc]init];
    [self presentViewController:spc animated:NO completion:^{
        [userInfo setValue:nil forKey:@"token"];
        [userInfo setValue:nil forKey:@"login"];
        NSMutableDictionary * data = [OpertionPlist readDataFromPlist];
        [data setValue:nil forKey:HOUSEINFO];
        [data setValue:nil forKey:STAFFINFO];
        [data setValue:nil forKey:FAVERITCARD];
        [data setValue:nil forKey:COMMUNITYINFOFORKEY];
        [OpertionPlist writeDataToPlist:data];
        GesturePasswordController * gpc = [[GesturePasswordController alloc]init];
        [gpc clear];
        [userInfo setValue:@"0" forKey:@"gesture"];
    }];
}



#pragma mark - 点击事件
-(void)setClick
{
    SystemSetViewController * ssvc = [[SystemSetViewController alloc]init];
    ssvc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ssvc animated:YES];
}

-(void)callTap
{
    NSString *telUrl = [NSString stringWithFormat:@"telprompt://020-32209192"];
    NSURL *url = [NSURL URLWithString:telUrl];
    [[UIApplication sharedApplication] openURL:url];
}

#pragma mark -- 改变个人头像
-(void)changeTitleImg
{
    ChangeHeadImgViewController * chivc = [[ChangeHeadImgViewController alloc]init];
    chivc.imageUrlPath = headurl;
    chivc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chivc animated:YES];
    chivc.selectImgPath = ^(NSInteger imgPath)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld.png",(long)imgPath]];
        titleImgView.image = [UIImage imageWithContentsOfFile:filePath];
        NSDictionary * dataDict = [OpertionPlist readDataFromPlist];
        NSArray * imgArray = [dataDict objectForKey:HEADERIMG];
        headurl = [NSString stringWithFormat:@"%@",imgArray[imgPath]];
        [personTableView reloadData];
        [self getData];
    };
    
    chivc.postImgPath = ^(NSString * postImgPath)
    {
        headurl = [NSString stringWithFormat:@"%@",postImgPath];
        //        [titleImgView sd_setImageWithURL:[NSURL URLWithString:headurl] placeholderImage:[UIImage imageNamed:@"96人像"]];
        [personTableView reloadData];
        [self getData];
    };
}



#pragma mark - 通知方法，检查token值
-(void)tokenCheck
{
    @try {
        tokeCount ++;
        if (tokeCount == 1) {
            StartPageController * spc = [[StartPageController alloc]init];
            [[self topViewController] presentViewController:spc animated:YES completion:^{
                [PromptInfoView showMessage:NSLocalizedString(@"errorToken", nil)];
            }];
        }
    }
    @catch (NSException *exception) {
        StartPageController * spc = [[StartPageController alloc]init];
        [self presentViewController:spc animated:YES completion:^{
            [PromptInfoView showMessage:NSLocalizedString(@"errorToken", nil)];
        }];
    }
}

#pragma mark - 解决视图问题
- (UIViewController*)topViewController
{
    return [self topViewControllerWithRootViewController:self];
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController
{
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabBarController = (UITabBarController *)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}



-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}





@end


